package com.demo.datastructure.binarySearch;

/**
 * @author ljr
 * @version 1.0
 * @description: 查找最后一个大于给定值的元素
 * @date 2021/10/13 17:25
 */
public class BinarySearch16 {

    public static int bsearch(int[] nums, int target) {
        int low = 0, high = nums.length-1, n = high;
        while(low <= high) {
            int mid = low + (high - low >> 1);
            if(nums[mid] < target){
                if(mid == n || nums[mid+1] > target) return mid;
                else low = mid + 1;
            }else{
                high = mid - 1;
            }
        }
        return -1;
    }

    public static int bsearch2(int[] nums, int target) {
        int low = 0;
        int high = nums.length-1, n = nums.length;
        while(low <= high){
           int mid = low + (high - low >> 1);
           if(nums[mid] >= target){
              high = mid - 1;
           }else{
              low = mid + 1;
           }
        }
        if(low < n && low > 0) return low - 1;
        else return -1;
    }



    public static void main(String[] args) {
        //int[] nums = new int[]{1,3,5};
        int[] nums = new int[]{0,1,2,3,5,8,9};
        int index = BinarySearch16.bsearch2(nums,5);
        System.out.println(index);
    }

}
